/*
 *  XMPmediator.cpp
 *  openFrameworks
 *
 *  Created by Frederic Gmeiner on 02.07.09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "XMPmediator.h"

namespace abliefern {
	
	
	
	void XMPmediator::fillDatabaseTags(){
		
		_myDatabase.openDB();
		
		/* List dir */
		DIR.setVerbose(false);
		DIR.allowExt("xmp");
		nFiles = DIR.listDir("XMP");
		
		for(int i =0; i< nFiles; i++){
			
			std::vector<std::string> keywordsFromFile;
			keywordsFromFile = getKeywords(DIR.getPath(i));
			
			std::vector<std::string> tokens = tokenize(DIR.getName(i),"-");
			
			if(tokens.size() > 0 && keywordsFromFile.size() > 0){
				
				std::string projectNumberString = tokens.at(0).erase(0,2);
				
				int projectID = StringToInt(projectNumberString);
				
				_myDatabase.saveKeywords(keywordsFromFile, projectID);	
				
			}
		}
		
		
		_myDatabase.closeDB();
		
	}
	
	
	
	
	std::vector<std::string> XMPmediator::getKeywords(std::string theFilename){
		
		std::vector<std::string> _returnKeywords;
		std::string keyword;
		
		
		XML.loadFile(theFilename);
		
		XML.pushTag("xpacket",0);
		XML.pushTag("x:xmpmeta",0);
		XML.pushTag("rdf:RDF",0);
		XML.pushTag("rdf:Description",0);
		XML.pushTag("dc:subject",0);
		XML.pushTag("rdf:Bag",0);
		
		
		for(int i=0; i< XML.getNumTags("rdf:li");i++){
			
			keyword	= XML.getValue("rdf:li", "hello",i);
			
			_returnKeywords.push_back(keyword);
			
			
			
			
			/* Search */
			
			string str2 ("Büro");
			size_t found;
			
			// different member versions of find in the same order as above:
			found=keyword.find(str2);
			if (found!=string::npos){
				cout << "first 'needle' found at: " << int(found) << endl;
				printf("%s\n",keyword.c_str());

			}
			
		}
		
		return _returnKeywords;
		
		
		
		
		
	}
	
	std::vector<std::string> XMPmediator::tokenize (const std::string& str,const std::string& delimiters)
	{
		vector<string> tokens;
		string::size_type delimPos = 0, tokenPos = 0, pos = 0;
		
		if(str.length()<1)  return tokens;
		while(1){
			delimPos = str.find_first_of(delimiters, pos);
			tokenPos = str.find_first_not_of(delimiters, pos);
			
			if(string::npos != delimPos){
				if(string::npos != tokenPos){
					if(tokenPos<delimPos){
						tokens.push_back(str.substr(pos,delimPos-pos));
					}else{
						tokens.push_back("");
					}
				}else{
					tokens.push_back("");
				}
				pos = delimPos+1;
			} else {
				if(string::npos != tokenPos){
					tokens.push_back(str.substr(pos));
				} else {
					tokens.push_back("");
				}
				break;
			}
		}
		return tokens;
	}
	
	
	int XMPmediator::StringToInt(std::string stringValue)
	{
		std::stringstream ssStream(stringValue);
		int iReturn;
		ssStream >> iReturn;
		
		return iReturn;
	} 	
	
	
	
	
	
}